<script lang="ts" setup>
import { reactive, ref, computed, nextTick } from "vue"
import { type FormInstance, type FormRules, ElMessage } from "element-plus"
import { createBankApi, updateBankApi } from "@/api/calculator"

interface FormData {
  bank_name: string
}

interface OpenOptions {
  id?: number | string
  initialData?: Partial<FormData>
}

interface Emits {
  (e: "submit", data: FormData & { id?: number | string }): void
}

const emit = defineEmits<Emits>()

// 内部状态
const formRef = ref<FormInstance | null>(null)
const visibleRef = ref(false)
const currentUpdateId = ref<number | string | undefined>(undefined)

const formData = reactive<FormData>({
  bank_name: ""
})

const formRules: FormRules = reactive({
  bank_name: [{ required: true, trigger: "blur", message: "请输入银行名称" }]
})

const resetForm = () => {
  formData.bank_name = ""
  formRef.value?.clearValidate()
}

// 关闭弹窗（不做重置，重置放在关闭动画结束事件里）
const handleClose = () => {
  visibleRef.value = false
}

// 对话框真正关闭后触发（此时可安全重置）
const handleDialogClosed = () => {
  resetForm()
  currentUpdateId.value = undefined
}

const handleSubmit = () => {
  formRef.value?.validate((valid: boolean, fields) => {
    if (valid) {
      if (currentUpdateId.value !== undefined) {
        updateBankApi({
          bank_id: currentUpdateId.value,
          bank_name: formData.bank_name
        })
          .then(() => {
            ElMessage.success("更新成功")
            emit("submit", { bank_name: formData.bank_name })
            handleClose()
          })
          .catch((err) => {
            console.error("更新失败", err)
          })
      } else {
        createBankApi({
          bank_name: formData.bank_name
        })
          .then(() => {
            ElMessage.success("新增成功")
            emit("submit", { bank_name: formData.bank_name })
            handleClose()
          })
          .catch((err) => {
            console.error("新增失败", err)
          })
      }
    } else {
      console.error("表单校验不通过", fields)
    }
  })
}

// 暴露给父组件：打开
const open = (options?: OpenOptions) => {
  currentUpdateId.value = options?.id
  formData.bank_name = options?.initialData?.bank_name ?? ""
  visibleRef.value = true
  nextTick(() => formRef.value?.clearValidate())
}

// 暴露给父组件：关闭
const close = () => {
  handleClose()
}

// 计算属性
const isEdit = computed(() => currentUpdateId.value !== undefined)
const dialogTitle = computed(() => (isEdit.value ? "修改" : "新增"))

// 暴露方法给父组件
defineExpose({
  open,
  close,
  submit: handleSubmit,
  reset: resetForm
})
</script>

<template>
  <el-dialog
    :model-value="visibleRef"
    :title="dialogTitle"
    @update:model-value="handleClose"
    @close="handleDialogClosed"
    width="30%"
  >
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
      <el-form-item prop="bank_name" label="银行名称">
        <el-input v-model="formData.bank_name" placeholder="请输入" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleSubmit">确认</el-button>
    </template>
  </el-dialog>
</template>
